<template>
  <div class="pageHead">
    <router-link to="/" class="logo"><img :src="siteLogo"/></router-link>
    <div class="menu currentPair" @mouseover="isShowPairList = true, initFirstScroll()" @mouseoout="isShowPairList = false">
      <div class="caption symbol"><span class="text">{{currentPair.Symbol}}</span><i class="arrow"></i></div>
      <div class="panel pairsBox" v-show="isShowPairList">

        <div class="tabTitle">
          <span
            :class="{item: true, active: currentPairCateIndex === -1}"
            @click="currentPairCateIndex = -1, initScroll($event)"
          >
            <img src="../../../assets/images/head/star.png" v-show="!favoriteList.length">
            <img src="../../../assets/images/head/star-active.png" v-show="favoriteList.length">
          </span>
          <span
            v-for="(item, index) in VarietyGroupList"
            v-text="item.Name"
            :class="{item: true, active: currentPairCateIndex === index}"
            @click="currentPairCateIndex = index, initScroll($event)"
          ></span>
        </div>

        <div class="pairCaption">
          <span class="item" :style="{width: pairCaptionWidths.star}">&nbsp;</span>
          <span class="item" :style="{width: pairCaptionWidths.market}">{{lang['tradingPage head pair']}}</span>
          <span class="item" :style="{width: pairCaptionWidths.price}">{{lang['price']}}</span>
          <span class="item" :style="{width: pairCaptionWidths.rose}">{{lang['24h Change']}}</span>
          <span class="item" :style="{width: pairCaptionWidths.volume}">24h {{lang['trading page volume']}}</span>
        </div>

        <!--start 下面两块html是一样的，要记得同时修改，因为数据源不同所以需要分别渲染-->
        <!--收藏列表-->
        <ul class="pairList" v-show="currentPairCateIndex === -1">
          <li
            v-for="item in favoriteList"
            :class="{active: currentPair.TradingConfigID === item.TradingConfigID}"
            @click="switchPair(item)">
            <!--下面是一样的-->
            <span class="star" :class="{active: item.isFavored}" :style="{width: pairCaptionWidths.star}" @click.stop="favor(item)">&nbsp;</span>
            <span class="market" :style="{width: pairCaptionWidths.market}" v-text="item.Symbol"></span>
            <span class="price" :style="{width: pairCaptionWidths.price}">{{item.Newest | formatCurrency(item)}}<span>&nbsp;&nbsp;<!--/&nbsp;&nbsp;￥{{item.Newest | formatMulCurrency(CNYRate, item)}}--></span></span>
            <span class="rose" :class="{up: item.roseVal > 0, down: item.roseVal < 0, noChange: item.roseVal === 0}" :style="{width: pairCaptionWidths.rose}">{{item.roseStr}}</span>
            <span class="volume" :style="{width: pairCaptionWidths.volume}">{{item.Last24TradeQuantity | formatCurrency(item, 'quantity')}} {{item.SellerCoinCode}}</span>
          </li>
        </ul>

        <!--交易对分类列表-->
        <ul class="pairList" v-for="(cate, index) in VarietyGroupList" v-show="currentPairCateIndex === index">
          <li
            v-for="item in cate.TradeVarietyList"
            :class="{active: currentPair.TradingConfigID === item.TradingConfigID}"
            @click="switchPair(item)">
            <!--下面是一样的-->
            <span class="star" :class="{active: item.isFavored}" :style="{width: pairCaptionWidths.star}" @click.stop="favor(item)">&nbsp;</span>
            <span class="market" :style="{width: pairCaptionWidths.market}" v-text="item.Symbol"></span>
            <span class="price" :style="{width: pairCaptionWidths.price}">{{item.Newest | formatCurrency(item)}}<span>&nbsp;&nbsp;<!--/&nbsp;&nbsp;￥{{item.Newest | formatMulCurrency(CNYRate, item)}}--></span></span>
            <span class="rose" :class="{up: item.roseVal > 0, down: item.roseVal < 0, noChange: item.roseVal === 0}" :style="{width: pairCaptionWidths.rose}">{{item.roseStr}}</span>
            <span class="volume" :style="{width: pairCaptionWidths.volume}">{{item.Last24TradeQuantity | formatCurrency(item, 'quantity')}} {{item.SellerCoinCode}}</span>
          </li>
        </ul>
        <!--end-->

      </div>
    </div>
    <div class="currentPairInfo">
      <p v-if="currentPair.BuyerCoinCode !== 'VUSD' && currentPair.BuyerCoinCode !== 'USD' && currentPair.BuyerCoinCode !== 'USDT'">
        <span>{{lang['new price']}}</span>
        <span :class="{up: currentPair.roseVal >= 0, down: currentPair.roseVal < 0, noChange: currentPair.roseVal === 0}">
          <i v-show="currentPair.roseVal"></i>
          {{currentPair.Newest | formatCurrency(currentPair)}} &nbsp;&nbsp; {{currentPair.LastUSDPrice | formatCurrency(currentPair) | currency('USD', '$', 4)}}
        </span>
      </p>
      <p v-else>
        <span>{{lang['new price']}}</span>
        <span :class="{up: currentPair.roseVal >= 0, down: currentPair.roseVal < 0, noChange: currentPair.roseVal === 0}">
          <i v-show="currentPair.roseVal"></i>
          {{currentPair.Newest | formatCurrency(currentPair)}}
        </span>
      </p>
      <p>
        <span>{{lang['24h Change']}}</span>
        <span :class="{up: currentPair.roseVal > 0, down: currentPair.roseVal < 0, noChange: currentPair.roseVal === 0}">
          {{currentPair.roseStr}}
        </span>
      </p>
      <p>
        <span>{{lang['highest price']}}</span>
        <span class="up">{{currentPair.High | formatCurrency(currentPair)}}</span>
      </p>
      <p>
        <span>{{lang['lowest price']}}</span>
        <span class="down">{{currentPair.Low | formatCurrency(currentPair)}}</span>
      </p>
      <p class="max">
        <span>24h {{lang['trading page volume']}}</span>
        <span class="noChange">
          {{currentPair.Last24TradeQuantity | formatCurrency(currentPair, 'quantity')}}
        </span>
      </p>
    </div>
    <div class="menuCenter max">
      <ul>
        <li><router-link to="/fiat/index" class="ctc">{{lang['headerNavLCTransact']}}</router-link></li>
        <li class="active"><router-link to="/trading">{{lang['headerNavTransact']}}</router-link></li>
      </ul>
    </div>
    <div class="right max">
      <Assets :lang="lang" :userInfo="mixUserInfo"></Assets>
      <div class="menu userMenu" v-if="!mixUserInfo.userName">
        <div class="caption noLogin">
          <router-link :to="{path: '/user/login', query: {from: $route.name}}">{{lang.headerLogin}}</router-link>
          <i class="line"></i>
          <router-link :to="{path: '/user/register', query: {from: $route.name}}" class="a2">{{lang.headerRegistration}}</router-link>
        </div>
      </div>
      <div class="menu userMenu" v-if="mixUserInfo.userName">
        <div class="caption">
          <i class="icon"></i>
          <span class="text">{{mixUserInfo.userName}}</span>
          <i class="arrow"></i>
        </div>
        <div class="panel " :style="{width: faWidth}">
          <router-link to="/safety" class="safe">{{lang.headerAccountSecurity}}</router-link>
          <a class="exit" @click="handleLogout">{{lang.headerExct}}</a>
        </div>
      </div>
      <div class="langMenu" @mouseover="isShowLangList = true" @mouseout="isShowLangList = false">
        <p class="selectedLanguage">
          <img class="contryContent" :src="currentLanguage.pic">
          <span>{{currentLanguage.name}}</span>
          <i :class="{active: isShowLangList}"></i>
        </p>
        <ul v-show="isShowLangList" class="languageList">
          <li v-for="(item, key, index) in languageList" @click="switchLanguage(key)" v-if="langSting && langSting.indexOf(key) > -1" :key="index"><img :src="item.pic">{{item.name}}</li>
        </ul>
      </div>
    </div>
    <!-- 适配头部 -->
    <div class="right min">
      <Assets :lang="lang" :userInfo="mixUserInfo"></Assets>
      <div class="menu userMenu menu-icon" @click="openMenu()">
        <img src='../images/menu-icon.png' />
      </div>

      <div class="submenu" v-show="open">
        <div class="nav">
          <div class="btn">
            <router-link to="/fiat/index" class="linkitem">{{lang['headerNavLCTransact']}}</router-link>
            <router-link to="/trading"  class="linkitem">{{lang['headerNavTransact']}}</router-link>
          </div>
          <div class="right">
            <div class="user-info">
              <!-- 未登录 -->
              <div class="menu userMenu" v-if="!mixUserInfo.userName">
                <div class="caption noLogin">
                  <router-link :to="{path: '/user/login', query: {from: $route.name}}">{{lang.headerLogin}}</router-link>
                  <router-link :to="{path: '/user/register', query: {from: $route.name}}" class="a2">{{lang.headerRegistration}}</router-link>
                </div>
              </div>
              <!-- 已登录 -->
              <div class="menu userMenu" v-if="mixUserInfo.userName">
                <div class="caption">
                  <i class="icon"></i>
                  <span class="text">{{mixUserInfo.userName}}</span>
                  <i class="arrow"></i>
                </div>
                <div class="panel " :style="{width: faWidth}">
                  <router-link to="/safety" class="safe">{{lang.headerAccountSecurity}}</router-link>
                  <a class="exit" @click="handleLogout">{{lang.headerExct}}</a>
                </div>
              </div>
            </div>
            <!-- 切换语言 -->
            <div class="langMenu" @mouseover="isShowLangList = true" @mouseout="isShowLangList = false">
              <p class="selectedLanguage">
                <img class="contryContent" :src="currentLanguage.pic">
                <span>{{currentLanguage.name}}</span>
                <i :class="{active: isShowLangList}"></i>
              </p>
              <ul v-show="isShowLangList" class="languageList">
                <li v-for="(item, key, index) in languageList" @click="switchLanguage(key)" v-if="langSting && langSting.indexOf(key) > -1" :key="index"><img :src="item.pic">{{item.name}}</li>
              </ul>
            </div>
          </div>
        </div>
        <div class="full" @click="openMenu()"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import Utils from '@/utils/Utils.js'
import Decimal from '@/libs/decimal.min.js'
import commonFilter from '@/filters/common.js'
import Assets from './Assets.vue'
import EventBus from '@/service/EventBus.js'
import realtimePush from './../js/realtimePush.js'
import ModalApi from '@/components/SwModal/api.js'
import LoginService from '@/service/LoginService.js'
import $ from 'jquery'
export default {
  components: {
    Assets
  },
  data () {
    return {
      VarietyGroupList: [], // 分类
      TradeVarietyList: [], // 列表

      pairs: [],
      currentPair: {},
      pairCates: [],
      currentPairCateIndex: 0,
      favoriteList: [],
      isShowLangList: false,
      inited: false,
      CNYRate: 1,
      pairCaptionWidths: {
        star: '40px',
        market: '96px',
        price: '120px',
        rose: '124px',
        volume: ''
      },
      isShowPairList: false,
      defaultCurrencyID: '',
      languageList: {
        'en': {
          name: 'English',
          pic: require('../../../assets/images/language/english.png')
        },
        'zh-CN': {
          name: '中文简体',  // this.lang.headerLanguangChinas
          pic: require('../../../assets/images/language/chinese.png')
        },
        'zh-Hant': {
          name: '中文繁体',  // this.lang.headerLanguangChinas
          pic: require('../../../assets/images/language/chinese.png')
        },
        'ja': {
          name: '日本語',
          pic: require('../../../assets/images/language/japanese.png')
        },
        'ko': {
          name: '한국어',
          pic: require('../../../assets/images/language/korean.png')
        },
        'fr': {
          name: 'Français',
          pic: require('../../../assets/images/language/french.png')
        },
        'nl': {
          name: 'Nederlands',
          pic: require('../../../assets/images/language/nederlands.png')
        },
        'vi': {
          name: 'Tiếng Việt',
          pic: require('../../../assets/images/language/vietnamese.png')
        },
      },
      currentLanguage: {},
      faWidth: 'auto',
      open: false
    }
  },
  props: [
    'lang'
  ],
  watch: {
    langKey () {
      this.currentLanguage = this.languageList[this.langKey]
    },
    pairs (nv) {
      EventBus.$emit('updatePairs', nv)
    },
    currentPair: {
      handler: (a, b) => {
        EventBus.$emit('updateCurrentPair', a)
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters({
      langKey: 'langKey',
      mixUserInfo: 'userInfo',
      customInfo: 'customInfo'
    }),
    langSting: function () {
      return this.customInfo.Languages
    },
    siteLogo: function () {
      return this.customInfo.Logo1 ? this.customInfo.Logo1 : require('../../../assets/images/logo.png')
    }
  },
  created () {
    this.currentLanguage = this.languageList[this.langKey]
  },
  filters: {
    // formatMulCurrency (a, b, item) {
    //   let precision = item.buyerPrecision
    //   a = new Decimal(a)
    //   a = a.mul(b).toFixed()
    //   return commonFilter.currency(commonFilter.fillDecimal(a, precision), 'USD', '', precision)
    // },
    formatCurrency (value, item, type) {
      let precision = item.buyerPrecision
      type === 'quantity' && (precision = 2) // 过年前陈总说数量是两位
      return commonFilter.currency(commonFilter.fillDecimal(new Decimal(parseFloat(value) || 0).toFixed(10), precision), 'USD', '', precision)
    }
  },
  methods: {
    ...mapActions([ 'switchLang', 'logout' ]),
    openMenu () {
      this.open = !this.open
      EventBus.$emit('menuOpen', this.open)
    },
    addPairKey () {
      // 增加key value方便查找
      this.pairs.forEach((v) => {
        Object.defineProperty(this.pairs, v.TradingConfigID, {
          Enumerable: false,
          value: v
        })
        Object.defineProperty(this.pairs, v.Symbol.replace('/', '_').toUpperCase(), { // BTC/USD => BTC_USD
          Enumerable: false,
          value: v
        })
      })
    },
    init () {
      // 获取默认交易配置, TradingType：0、虚拟币-货币交易。 2、虚拟币-虚拟币交易
      return this.$http.post('Trade/GetTradeConfig', {}, {
        // mock: 'GetTradeConfig'
      })
    },
    classifyPair () {
      let cates = []
      let cated = {}
      let buyer
      this.pairs.forEach((pair) => {
        buyer = pair.BuyerCoinCode
        if (!cated[buyer]) {
          cates.push(buyer)
          cated[buyer] = true
        }
      })
      this.pairCates = cates
    },
    favor (item) {
      this.$http.post('UserTransaction/AddOrDelete', {
        configId: item.TradingConfigID,
        collectionType: item.isFavored ? 2 : 1 // 1 加入收藏；2 取消收藏
      }).then((res) => {
        if (res.StatusCode === '200') {
          if (!item.isFavored) this.favoriteList.push(item)
          if (item.isFavored) {
            this.favoriteList.splice(this.favoriteList.findIndex((favoritePair) => favoritePair.TradingConfigID === item.TradingConfigID), 1)
          }
          item.isFavored = !item.isFavored
          // this.$set(this.paris, this.pairs.findIndex((pair) => pair.TradingConfigID === item.TradingConfigID), item)
          this.setFavoriteStatusForPairs()
        }
      })
    },
    getFavoriteList () {
      this.$http.post('UserTransaction/GetUserTransactionList', {}, {
        isDisposeCode: false
      }).then((res) => {
        let ids = res.Data || []
        let list = []
        ids.forEach((id) => {
          list.push(this.pairs[id])
        })
        this.favoriteList = list
        this.setFavoriteStatusForPairs()
      })
    },
    setFavoriteStatusForPairs () {
      this.pairs.forEach((pair, index) => {
        let isFavored = false
        this.favoriteList.forEach((favoritePair) => {
          pair.TradingConfigID === favoritePair.TradingConfigID && (isFavored = true)
        })
        pair.isFavored = isFavored
        // this.$set(this.pairs, index, pair)
      })
    },
    setPrecisionWithArray (list = [], key, name) {
      list.forEach((item) => {
        // 防-1e8
        let prec = new Decimal(item[key])
        prec = prec.toFixed()
        if (prec.toString().split('.').length > 1) {
          prec = prec.toString().split('.')[1].length
        } else {
          prec = 2
        }
        item[name] = prec
      })
    },
    switchPair (pair) {
      this.isShowPairList = false

      let pairStr = pair.Symbol.replace('/', '_').toUpperCase()
      // 注意，用此句代码修改后发现刷新后不会触发vue路由，只有跳转才有效
      history.replaceState(null, '', '/trading/' + pairStr)
      // 交易对存本地
      Utils.LS.set('tradingPair', pairStr)

      this.currentPair = pair

      EventBus.$emit('switchPair', this.currentPair)

      if (this.inited) {
        realtimePush.switchPrecision(this.currentPair.TradingConfigID, this.currentPair.buyerPrecision)
        realtimePush.switchPair(this.currentPair.TradingConfigID)
      }

      this.inited = true
    },
    updatePairsByPush (newPairs) {
      for (let i = 0; i < newPairs.length; i++) {
        for (let j = 0; j < this.pairs.length; j++) {
          if (newPairs[i].TradingConfigID === this.pairs[j].TradingConfigID) {
            this.pairs[j].Newest = newPairs[i].Newest
            this.pairs[j].Rose = newPairs[i].Rose
            this.pairs[j].Rise = newPairs[i].Rise
            this.pairs[j].High = newPairs[i].Highest
            this.pairs[j].Low = newPairs[i].Low
            this.pairs[j].LastUSDPrice = newPairs[i].LastUSDPrice
            this.pairs[j].Last24TradeQuantity = newPairs[i].Last24TradeQuantity
          }
        }
      }
      this.setRoseWithArray(this.pairs) // 统一格式化rose
    },
    // 格式化Rose即涨幅的符号、百分比%和涨跌量
    setRose (item) {
      let rose
      let sign
      rose = new Decimal(item.Rose || 0)
      rose = parseFloat(rose.mul(100).toFixed(2))
      rose > 0 && (sign = '+')
      rose < 0 && (sign = '-')
      rose === 0 && (sign = '')
      return {
        sign,
        rose,
        str: sign + commonFilter.fillDecimal(rose, 2).replace('-', '') + '%' // fillDecimal是补0
      }
    },
    setRoseWithArray (arr = []) {
      let roseParams
      arr.forEach((item, index) => {
        roseParams = this.setRose(item)
        item.roseVal = roseParams.rose
        item.roseSign = roseParams.sign
        item.roseStr = roseParams.str
        // this.$set(arr, index, item)
      })
    },
    switchLanguage (language, dflang) {
      this.currentLanguage = this.languageList[language]
      // 更改语言
      this.switchLang(language)
      this.isShowLangList = false
    },
    handleLogout () {
      LoginService.logout()
      this.$router.push({path: '/user/login'})
    },
    // 初始化第一个pairList滚动条
    initFirstScroll ($event) {
      this.$nextTick(() => {
        this.initScroll({target: $('.pageHead .tabTitle .item')[0]})
      })
    },
    // 初始化各个交易列表的滚动条
    initScroll ($event) {
      this.$nextTick(() => {
        let $pairList = $($event.target).closest('.panel').find('.pairList:visible')
        if ($pairList.height() > 400) {
          $pairList.height('400px').niceScroll({autohidemode: false}).resize()
        }
      })
    }
  },
  mounted () {
    this.init().then((res) => {
      this.VarietyGroupList = res.Data.VarietyGroupList
      // let _tradeVarietyList = [] // res.Data.TradeVarietyList

      let _pairs = []
      for (var i = 0; i < this.VarietyGroupList.length; i++) {
        let _data_ = this.VarietyGroupList[i].TradeVarietyList
        for (let j = 0; j < _data_.length; j++) {
          _pairs.push(_data_[j])
        }

        this.setRoseWithArray(_data_) // 统一格式化rose

        // 后台会输出0.00000001为1e-8，要用第三库转
        this.setPrecisionWithArray(res.Data.VarietyGroupList[i].TradeVarietyList, 'MinSellerCoinPrecision', 'sellerPrecision')
        this.setPrecisionWithArray(res.Data.VarietyGroupList[i].TradeVarietyList, 'MinBuyerCoinPrecision', 'buyerPrecision')
      }

      this.pairs = _pairs
      this.addPairKey(this.pairs) // 添加key，方便查找pair
      // this.CNYRate = res.Data.CNYExchangeRate
      this.classifyPair()
      this.getFavoriteList()
      this.defaultCurrencyID = res.Data.DefaultCurrencyID // 用于计算默认货币总折合
      // 重点：从pairs筛选出来的pair，赋值给currentPair，currentPair经过vue的响应式格式化后，currentPair已不是原来pairs筛选出来的pair
      this.currentPair = this.pairs.find((v) => v.TradingConfigID === res.Data.DefaultTradeConfigID)
      // 本地读取pair
      let localPair = Utils.LS.get('tradingPair')
      // 读取url里的piar
      let urlPair = this.$route.params.pair ? this.$route.params.pair.toUpperCase() : ''
      // url优于本地
      let specifiedPair = urlPair || localPair
      this.switchPair(this.pairs[specifiedPair] || this.currentPair)

      EventBus.$emit('sendPairsToTrade', this.pairs, this.defaultCurrencyID) // 计算资产总折合

      let that = this
      realtimePush.init({
        address: res.Data.Signalr,
        userId: this.mixUserInfo.userId,
        pairId: this.currentPair.TradingConfigID,
        RealTrendCallback: (result) => {
          this.updatePairsByPush(result)
          EventBus.$emit('sendPairsToTrade', this.pairs, this.defaultCurrencyID) // 计算资产总折合
        },
        KLinesDataCallback: (result) => {
          EventBus.$emit('pushKline', result)
        },
        OrderStatusCallback: (result) => {
          EventBus.$emit('pushOrderBookList', result)
        },
        DealCallback: (result) => {
          EventBus.$emit('pushTradeRecordDetailList', result)
        },
        OrderBookCallback: (result) => {
          EventBus.$emit('pushOrderBook', result)
        },
        TradesCallback: (result) => {
          EventBus.$emit('pushRrealtimeTradeList', result)
        },
        SendOrderResult: (result) => {
          for (let i = 0; i < result.length; i++) {
            if (result[i].StatusCode === '200') {
              ModalApi.message(this.lang['checkout success'])
            } else {
              ModalApi.message(this.lang[result[i].StatusCode])
            }
          }
        },
        AssetsChangedCallback: (result) => {
          EventBus.$emit('pushAssets', result)
        },
        onReady () {
          realtimePush.switchPrecision(that.currentPair.TradingConfigID, that.currentPair.buyerPrecision)
        }
      })
    })

    this.faWidth = $('.userMenu').width() + 'px'
    setTimeout(() => {
      $('.pairsBox').css({left: -$('.caption').offset().left + 8})
    }, 200)
  }
}
</script>
<style lang="less">
@import './../css/head.less';
</style>
